//
//  LZGroupListViewController.m
//  laziz_Consumer
//
//  Created by xbn_iMac on 2016/11/17.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZGroupListViewController.h"
#import "UITableView+LZTableView.h"
#import "LZGroupListViewTableViewCell.h"
#import "LZGroupDetailViewController.h"
#import "LZGroupListModel.h"
#import "XBNTimeLimitCountDownCalculator.h"
#import "LZTimeLimitCountDownJudgeDataManager.h"
#import "LZAlertView.h"
#import "LZGrouponPresenter.h"
#import "TShareView.h"
#import "TShareEventHandler.h"
#import "LZNoDataPublicView.h"
#import "MJRefresh.h"

@interface LZGroupListViewController ()<UITableViewDelegate,UITableViewDataSource,LZGroupListViewTableViewCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UILabel *labTimeCountDown;

@property (assign, nonatomic) NSTimeInterval nowTime;
@property (assign, nonatomic) NSTimeInterval endTime;
@property (strong, nonatomic) NSMutableArray *arrData;

@property (strong, nonatomic) XBNTimeLimitCountDownCalculator *timeCountDownCalculator;

@property (nonatomic, assign) BOOL isTimeEnd;   // 时间是否结束了

@property (nonatomic, strong) TShareView * shareView;

@property (nonatomic, assign) int page;
@property (nonatomic, assign) int limit;

@property (nonatomic, assign) NSTimeInterval request_timeStemp;

@end

@implementation LZGroupListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"团购列表页面";
    
    self.title = LZLocalizedString(@"group_join", nil);
    
    self.view.backgroundColor = UIColorFromRGB(0xf2f2f2, 1);
    
    [self registCell];
    
    [self configBaseData];
    
    [self.table.mj_footer beginRefreshing];
    // Do any additional setup after loading the view from its nib.
}

- (void)dealloc {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - request

- (void)upLoadMoreData {
    [self requestGroupList];
}
// 团购列表
- (void)requestGroupList {
    WS(weakSelf)
    [LZGrouponPresenter getVideoGroupListWithPromotionID: self.videoId PageNum:self.page PageLimit:self.limit TimeStamp:[NSNumber numberWithLong:self.request_timeStemp] ResultSuccess:^(NSArray *listArr,NSNumber *startTime,NSNumber *endTime) {
        
        [weakSelf.table.mj_footer endRefreshing];
        
        if (weakSelf.nowTime<=0) {
            weakSelf.nowTime = [startTime longLongValue]/1000;
        }
        
        if (weakSelf.endTime<=0) {
            weakSelf.endTime = [endTime longLongValue]/1000;
        }
        
        if (weakSelf.nowTime>0 && weakSelf.endTime>0 && weakSelf.timeCountDownCalculator == nil) {
            [weakSelf startTimeCountDown];
        }
        weakSelf.page ++;
        
        if (weakSelf.request_timeStemp <= 0) {
            weakSelf.request_timeStemp = [startTime longLongValue];
        }
        
        if (listArr && listArr.count>0) {
            [weakSelf.arrData addObjectsFromArray:listArr];
            [weakSelf.table reloadData];
        }
        else {
            if (weakSelf.arrData.count == 0) {
                [weakSelf.table setNullStringFooterText];
            }
            else {
                [weakSelf.table setNoMoreDataFooterText];
            }
            weakSelf.table.mj_footer.state = MJRefreshStateNoMoreData;
        }
        
        if (weakSelf.arrData.count == 0) {
            [LZNoDataPublicView showNoDataViewInView:weakSelf.table];
        }
        else {
            [LZNoDataPublicView hiddenNoDataViewInView:weakSelf.table];
        }
       
    } ResultFailed:^(NSString *remind) {
        
    }];
}

// 参团
- (void)requestJoinGroupon:(LZGroupListModel*)model {
    
    WS(weakSelf)
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    [LZGrouponPresenter joinGrouponWithGroupID:model.groupId SellerID:model.sellerId PromotionID:model.promotionId GrouponCount:[NSString stringWithFormat:@"%ld",model.grouponCount] ResultSuccess:^(id result) {
        
        [weakSelf stopLoadingViewForView:self.view];

        if ([result[@"statusCode"] integerValue] == kCodeSuccesss) {
            
            // 先更新model
            model.peopleCount = model.peopleCount+1;
            model.isGroupon = YES;
            
            [weakSelf.table reloadData];
            // 剩余人数
            NSString *residue = [NSString stringWithFormat:@"%ld",model.grouponCount - model.peopleCount];
            
            if ([residue integerValue] == 0) {
                // 如果正好是最后一个人
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:[NSString stringWithFormat:LZLocalizedString(@"group_join_success", nil),residue] andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                [alert show];
                alert.clickButtonIndexBlock = ^(NSInteger index) {
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                };
            }
            else {
                // 弹出提示框
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:[NSString stringWithFormat:LZLocalizedString(@"group_join_success_remind", nil),residue] andImage:nil cancelButtonTitle:LZLocalizedString(@"group_later", nil) otherButtonTitles:LZLocalizedString(@"group_invite", nil),nil];
                [alert show];
                
                alert.clickButtonIndexBlock = ^(NSInteger index) {
                    if (index == 0) {
                        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    }
                    else {
                        [weakSelf openShareWithShareImageUrl:result[@"data"] andGroupName:model.groupName];
                    }
                };
            }
            
        }else{
            NSString *status = result[@"statusCode"];
            
            if (![LZBasePresenter checkAuthorStatus:status]) {
                return;
            }
            
            if ([status isEqualToString:@"0500025"]) {
                DLog(@"用户已参加过该优惠");
                model.isGroupon = YES;
                
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"group_joined_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                [alert show];
                
                WS(weakSelf)
                alert.clickButtonIndexBlock = ^(NSInteger index) {
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                };
            }
        }
    } ResultFailed:^(NSString *remind) {
        [weakSelf stopLoadingViewForView:self.view];
    }];
}

#pragma mark - 初始化数据

- (void)configBaseData {
    self.arrData = [NSMutableArray array];
    self.page = 1;
    self.limit = 10;
    self.nowTime = 0;
    self.endTime = 0;
    self.request_timeStemp = 0;
    [LZTimeLimitCountDownJudgeDataManager configLimitedLabel:self.labTimeCountDown withReamin:0 andDayUnit:@"d " HourUnit:@"h " andMinuteUnit:@"m " andSecUnit:[NSString stringWithFormat:@"s %@",LZLocalizedString(@"group_left", nil)] andIsChangeUintColor:YES andDayUnitColor:UIColorFromRGB(0x999999, 1) HourUnitColor:UIColorFromRGB(0x999999, 1) andMinUnitColor:UIColorFromRGB(0x999999, 1) andSecUnitColor:UIColorFromRGB(0x999999, 1)];
    
    self.table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMoreData)];
    [self.table configFooterRefreshText];
}


- (void)registCell {
    self.table.backgroundColor = UIColorFromRGB(0xf2f2f2, 1);
    self.table.backgroundView.backgroundColor = [UIColor clearColor];
    self.table.separatorColor = [UIColor clearColor];
    [self.table registerNib:[UINib nibWithNibName:@"LZGroupListViewTableViewCell" bundle:nil] forCellReuseIdentifier:@"LZGroupListViewTableViewCell"];
}

- (void)startTimeCountDown {
    if (self.timeCountDownCalculator) {
        return;
    }
    // ******************** 创建计时器 ********************
    self.timeCountDownCalculator = [XBNTimeLimitCountDownCalculator new];

    // 取出服务器时间
    self.timeCountDownCalculator.remainTimeInterval = self.nowTime;
    
    // ********************** 计时器 **********************
    self.timeCountDownCalculator.remainTimeInterval = self.endTime - self.nowTime;

    if (self.timeCountDownCalculator.remainTimeInterval<=0) {
        [LZTimeLimitCountDownJudgeDataManager configLimitedLabel:self.labTimeCountDown withReamin:0 andDayUnit:@"d " HourUnit:@"h " andMinuteUnit:@"m " andSecUnit:[NSString stringWithFormat:@"s %@",LZLocalizedString(@"group_left", nil)] andIsChangeUintColor:YES andDayUnitColor:UIColorFromRGB(0x999999, 1) HourUnitColor:UIColorFromRGB(0x999999, 1) andMinUnitColor:UIColorFromRGB(0x999999, 1) andSecUnitColor:UIColorFromRGB(0x999999, 1)];
    }
    else {
        WS(weakSelf);

        [self.timeCountDownCalculator addProcessBlock:^(NSTimeInterval remain) {
            //        DLog(@"计时进行中 %f",remain);
            if (remain<0) {
                [LZTimeLimitCountDownJudgeDataManager configLimitedLabel:weakSelf.labTimeCountDown withReamin:0 andDayUnit:@"d " HourUnit:@"h " andMinuteUnit:@"m " andSecUnit:[NSString stringWithFormat:@"s %@",LZLocalizedString(@"group_left", nil)] andIsChangeUintColor:YES andDayUnitColor:UIColorFromRGB(0x999999, 1) HourUnitColor:UIColorFromRGB(0x999999, 1) andMinUnitColor:UIColorFromRGB(0x999999, 1) andSecUnitColor:UIColorFromRGB(0x999999, 1)];
                [weakSelf.timeCountDownCalculator timeLimitCountDownClear];
            }
            else {
                [LZTimeLimitCountDownJudgeDataManager configLimitedLabel:weakSelf.labTimeCountDown withReamin:remain andDayUnit:@"d " HourUnit:@"h " andMinuteUnit:@"m " andSecUnit:[NSString stringWithFormat:@"s %@",LZLocalizedString(@"group_left", nil)] andIsChangeUintColor:YES andDayUnitColor:UIColorFromRGB(0x999999, 1) HourUnitColor:UIColorFromRGB(0x999999, 1) andMinUnitColor:UIColorFromRGB(0x999999, 1) andSecUnitColor:UIColorFromRGB(0x999999, 1)];
            }

        } cancelBlock:^{
            //        DLog(@"结束了");
        }];
        
        [self.timeCountDownCalculator timeLimitCountDownResume];
    }
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arrData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LZGroupListViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LZGroupListViewTableViewCell"];
    cell.delegate = self;
    cell.indexPath = indexPath;
    LZGroupListModel *model = self.arrData[indexPath.section];
    cell.model = model;
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 150;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01;
    }
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    view.tintColor = [UIColor clearColor];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LZGroupListModel *model = self.arrData[indexPath.section];
    if (self.endTime<=self.nowTime) {
        self.isTimeEnd = YES;
        [self showClosedAlertWithIndexPath:indexPath];
        return;
    }
    else if (model.peopleCount == model.grouponCount) {
        [self showClosedAlertWithIndexPath:indexPath];
        return;
    }
    

    LZGroupDetailViewController *vc = [[LZGroupDetailViewController alloc] init];
    [vc startCountDownReamin:self.timeCountDownCalculator];
    vc.grouponId = [model.groupId copy];
    [self.navigationController pushViewController:vc animated:YES];
    
    WS(weakSelf)
    vc.fullUpBlock = ^(NSIndexPath *lzIndexPath) {
        LZGroupListModel *modelTemp = weakSelf.arrData[lzIndexPath.section];
        modelTemp.peopleCount = modelTemp.grouponCount;
        [weakSelf.table reloadData];
    };
}

#pragma mark - LZGroupListViewTableViewCellDelegate
-(void)clickJoinButtonAction:(LZGroupListModel*)model andIndexPath:(NSIndexPath *)indexPath {
    DLog(@"Join");
    if (self.endTime<=self.nowTime) {
        self.isTimeEnd = YES;
        [self showClosedAlertWithIndexPath:indexPath];
    }
    else if (model.peopleCount == model.grouponCount) {
        [self showClosedAlertWithIndexPath:indexPath];
        return;
    }
    else {
        [self requestJoinGroupon:model];
    }
}

#pragma mark - Share

- (TShareView *)shareView {
    
    if (_shareView == nil) {
        _shareView = [[TShareView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    
    return _shareView;
}

- (void)openShareWithShareImageUrl:(NSString*)shareImageUrl andGroupName:(NSString*)groupName {
    WS(weakSelf)
    [self.shareView shareViewOpen];
    self.shareView.shareViewButtonActionBlock = ^(TSHAREVIEW_BUTTON_TYPE type){
        [weakSelf shareAction:type andShareImageUrl:shareImageUrl andGroupName:groupName];
    };
    self.shareView.dismissViewBlock = ^() {
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    };
}

- (void)shareAction:(NSInteger)type andShareImageUrl:(NSString*)shareImageUrl andGroupName:(NSString*)groupName {
    /* 参团邀请 */
    SSDKPlatformType sharePlatformType = SSDKPlatformTypeUnknown;
    
    switch (type) {
        case 0:
            sharePlatformType = SSDKPlatformTypeSMS;
            break;
        case 1:
            sharePlatformType = SSDKPlatformTypeMail;
            break;
        case 2:
            sharePlatformType = SSDKPlatformTypeFacebook;
            break;
        case 3:
            sharePlatformType = SSDKPlatformTypeTwitter;
            break;
    }
    
    WS(weakSelf)
    [TShareEventHandler shareWithShareURL:nil
                            shareImageUrl:@[[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,shareImageUrl]]
                               shareTitle:LZLocalizedString(@"share_join_group_invite_title", nil)
                                shareText:[NSString stringWithFormat:LZLocalizedString(@"share_join_group_invite_content", nil),groupName]
                                shareType:sharePlatformType
                                  topView:nil
                               stateBlock:^(SSDKResponseState state) {
                                   DLog(@"%ld",state);
                                   if (weakSelf) {
                                       [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                                   }
                               }];
    
    [self.shareView shareViewClose];
}

#pragma mark - 弹Alert

-(void)showClosedAlertWithIndexPath:(NSIndexPath*)indexPath {
    
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"group_closed_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        //        NSLog(@"恩，确实点击了第%ld个按钮",(long)index);
        if (weakSelf.isTimeEnd) {
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }
    };
}

@end
